<?php


Class Convert{



    public $convert_info = [
        'convert_type' => 'convertaudio',
        'inputdir' => './data/',
        'outsuffix' => '',
    ];


    public $options = [];



    public function __construct($convert_info = [])
    {

        if(empty($convert_info['outsuffix'])) echo '抱歉,转换格式未设定';

        if(!empty($convert_info))$this->convert_info = array_merge($this->convert_info,$convert_info);
        $this->init();

    }


    public function init()
    {
        foreach ($this->getSupportCommand() as $value){
            if($value['type'] == $this->convert_info['convert_type']){
                $this->options = $value;
                break;
            }
        }
    }


    public function getCommands()
    {
        foreach ($this->getFilesRecursive() as $file){
            $pathinfo = pathinfo($file);
            $input = $file;
            $ouput_dir = dirname($file).'_result' . DIRECTORY_SEPARATOR ;
            if(!is_dir($ouput_dir))mkdir($ouput_dir,0777,true);
            $output = $ouput_dir . $pathinfo['filename'] .'_result.' . $this->convert_info['outsuffix'];
            $item_command = str_replace(['@input','@output'],[$input,$output],$this->options['command_temp']);
            $commands[] = $item_command;
        }

        return $commands;
    }

    public function getFilesRecursive() {
        $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($this->convert_info['inputdir']), RecursiveIteratorIterator::LEAVES_ONLY);
        $fileList = [];
        foreach ($files as $fileInfo) {
            if($fileInfo->getFileName() != '.' && $fileInfo->getFileName() != '..'){
                $fileList[] = $fileInfo->getPathname();
            }

        }


        return $fileList;

    }

    public function getSupportCommand()
    {
        $supper_command = [
            ['name'=>'转换格式','type'=>'format','command_temp'=>'ffmpeg -i @input @output'],
        ];

        return $supper_command;
    }
}


$obj = new Convert(['convert_type'=>'format','outsuffix'=>'mp3']);
$commands = $obj->getCommands();
foreach ($commands as $v){
    exec($v);
}

